<template>
  <div class="chart">
    <div class="chart-title">{{ title }}</div>
    <div ref="myChart" class="chart-content"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    title: {
      type: String,
      default: '柱状图'
    },
    options: {
      type: Object,
      default: () => ({
        color: '#f60',// 系列柱
        xAxis: {
          data: ['1月', '2月', '3月', '4月', '5月', '6月'],
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          }
        },
        yAxis: {
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          }
        },
        series: [
          {
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
          }
        ],
        grid: {
          left: '5%',
          right: '5%',
          top: '10%',
          bottom: '25%',
          containLabel: true
        }
      })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.init()
    this.bindResizeEvent()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    this.unbindResizeEvent()
  },
  methods: {
    init() {
      this.chart = echarts.init(this.$refs.myChart)
      this.chart.setOption(this.options)
    },
    bindResizeEvent() {
      this.handleResize = () => {
        if (this.chart) {
          this.chart.resize()
        }
      }
      window.addEventListener('chart-resize', this.handleResize)
      window.addEventListener('resize', this.handleResize)
    },
    unbindResizeEvent() {
      if (this.handleResize) {
        window.removeEventListener('chart-resize', this.handleResize)
        window.removeEventListener('resize', this.handleResize)
      }
    }
  }
}
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.chart-title {
  color: #fff;
  font-size: var(--chart-title-font-size, 16px);
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.chart-content {
  flex: 1;
  width: 100%;
  min-height: 200px;
}
</style>